package com.xfb.gateway.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: Xing Fang Bin
 * @Date: 2021/10/26/17:30
 * @Description:
 */
@Component
@RefreshScope
public class UserGlobalFilter implements GlobalFilter, Ordered {

    @Value("${lagou.time}")
    private int time;
    @Value("${lagou.count}")
    private int count;

    //key为IP，value为注册的次数
    private static Map<String, Integer> registerCountMap = new HashMap<>();
    //key为IP，value为注册最近一次的时间
    private static Map<String, Long> registerTimeMap = new HashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // token认证
        if (request.getURI().getPath().contains("/user/info")) {
            HttpCookie token = request.getCookies().getFirst("token");
            if (token == null || StringUtils.isEmpty(token.getValue())) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                String msg = "请登录！";
                DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes());
                return response.writeWith(Mono.just(wrap));
            }

        }

        //注册时验证
        if (request.getURI().getPath().contains("/user/register")) {
            // 从request对象中获取客户端ip
            String clientIp = request.getRemoteAddress().getHostString();

            //判断注册时间
            Long now = System.currentTimeMillis();
            if (registerTimeMap.containsKey(clientIp)) {
                Long lastTime = registerTimeMap.get(clientIp);
                if ((now - lastTime) < time * 1000) {
                    //判断注册次数
                    Integer times = registerCountMap.get(clientIp) + 1;
                    if (times > count) {
                        response.setStatusCode(HttpStatus.SEE_OTHER); // 状态码
                        String data = "同一IP，30S内最多只能新建2个账号!";
                        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                        return response.writeWith(Mono.just(wrap));
                    }
                    registerCountMap.put(clientIp, times);

                } else {
                    registerCountMap.put(clientIp, 1);
                }
            }
            registerTimeMap.put(clientIp, now);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
